Event.observe ( window, 'load', bootstrap );

function bootstrap () {
  $( 'datasheet' ).observe ( 'change', display_products );
  
  if ( $( 'datasheet' ).value != '' ) {
    display_products ();
  }
}

function display_products () {
  var datasheet = $( 'datasheet' ).value;
  
  if ( datasheet != '' ) {
    new Ajax.Request ( '/rest/datasheet/' + datasheet + '/products', {
      method         : 'get',
      requestHeaders : { Accept : 'application/json' },
      onCreate       : function () {
        $( 'products_table'      ).replace ( '<div id="products_table"></div>'  );
        $( 'isock_altnavigation' ).replace ( '<div id="isock_altnavigation" />' );
        
      /*display_progress ( 'Querying DB...' );*/
      },
      onFailure      : function () {
        $( 'products_table' ).replace ( '<p id="products_table" class="error">No products!</p>' );
      },
      onSuccess      : function ( transport ) {
        var products = transport.responseJSON.products;

        if ( products.length > 0 ) {
          $( 'products_table' ).replace ( products_as_html_table ( products, 'products_table', datasheet ) );
          
          TableKit.Sortable.init ( 'products_table' );
          TableKit.reload ();
          
          $( 'isock_altnavigation' ).replace (
              "<div id=\"isock_altnavigation\">\n"
            + "  <ul id=\"isock_altnavigation-index\">\n"
            + "    <li id=\"isock_altnavigation-index-toc\">Links</li>\n"
            + "    <li>Links</li>\n"
            + "    <li><a href=\"/datasheet/products?id=" + datasheet + "\">Self</a></li>\n"
            + "    <li><a href=\"/datasheet/commits?id="  + datasheet + "\">Commits</a></li>\n"
            + "  </ul>\n"
            + "</div>\n"
          );
        }
        else {
          $( 'products_table' ).replace ( '<p id="products_table" class="error">No products!</p>' );
        }
      },
      onComplete     : function () {
      /*hide_progress ();*/
      }
    } );
  }
}
